import XLSX from 'xlsx'
import { dateFilter, formatDate } from './index'
import store from "@/store"

/**
 * 获取表头（通用方式）
 */
export const getHeaderRow = (sheet: any) => {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) {
    /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}

export const isExcel = (file: File) => {
  return /\.(xlsx|xls|csv)$/.test(file.name)
}
// 格式化 将中文转成表中对应的英文字段
export const transition = (data: any, MAPPING_RELATIVES: any) => {
  // console.log(data)
  let arr: any = []
  data.forEach((item: any) => {
    const resultMap: any = {}
    // 参照MAPPING_RELATIVES 转成插入数组
    Object.keys(item).forEach((key) => {
      if (MAPPING_RELATIVES[key]) resultMap[MAPPING_RELATIVES[key]] = item[key]
      else resultMap[key] = item[key]

      if (MAPPING_RELATIVES[key] === 'status') {
        return item[key] === '正常'
          ? (resultMap[MAPPING_RELATIVES[key]] = true)
          : (resultMap[MAPPING_RELATIVES[key]] = false)
      }
      if (MAPPING_RELATIVES[key] === 'associateIds') {
        const roles = store.state.entireRoles
        const ids = mapping(roles, item, key, 'name')
        if (ids.length) {
          resultMap.associateIds = ids
        }
      }
      if (MAPPING_RELATIVES[key] === 'categories') {
        const categorys = store.state.entireCategorys
        const ids = mapping(categorys, item, key, 'name')
        if (ids.length) {
          resultMap.associateIds = ids
        }

      }
    })
    arr.push(resultMap)
  })
  return arr
}
// 导出 数据格式化成二维数组格式
export const formateJson = (MAPPING_RELATIVES: any, rows: any) => {
  return rows.map((item: any) => {
    return Object.keys(MAPPING_RELATIVES).map((key) => {
      // 嵌套要进行 打平
      if (MAPPING_RELATIVES[key] === 'userRoles') {
        const roles = item[MAPPING_RELATIVES[key]]
        return JSON.stringify(
          roles.map((item: any) => {
            return item.name
          })
        )
      }
      if (MAPPING_RELATIVES[key] == 'categories') {
        const categories = item[MAPPING_RELATIVES[key]]
        return JSON.stringify(
          categories.map((item: any) => {
            return item.name
          })
        )
      }

      if (MAPPING_RELATIVES[key] === 'createdAt') {
        return dateFilter(item[MAPPING_RELATIVES[key]])
      }

      if (MAPPING_RELATIVES[key] === 'status') {
        return item[MAPPING_RELATIVES[key]] == true
          ? (item[MAPPING_RELATIVES[key]] = '正常')
          : (item[MAPPING_RELATIVES[key]] = '停用')
      }

      return item[MAPPING_RELATIVES[key]]
    })
  })
}


/**
 *  多表关联的映射关系
 * @param roles 映射数组
 * @param item  映射的值
 * @param key   映射字段
 * @param name  映射关联字段
 * @returns
 */
function mapping(roles: any[], item: any, key: any, name: string) {
  let rolesMap = new Map()
  roles.forEach(item => rolesMap.set(item[name], item.id))
  let ids: any = []
  JSON.parse(item[key]).forEach((it: { [x: string]: any }) => {
    if (rolesMap.has(it)) {
      ids.push(rolesMap.get(it))
    }
  })
  return ids
}
